<template>
  <div class="search">
    <div class="seatop">
      <div class="inp">
        <input
          type="search"
          placeholder="请输入搜索内容"
          v-model="search"
          @keyup.enter="go()"
        />
      </div>
      <span @click="$router.go(-1)">取消</span>
    </div>
    <div class="content" v-if="show">
      <span>搜索历史</span>
      <div class="his">
        <div
          @click="storys(item)"
          class="history"
          v-for="item in history"
          :key="item"
        >
          {{ item }}
        </div>
      </div>
    </div>
    <KeepAlive>
      <searchData
        v-if="!show"
        :data="data"
        @onclick="changeSearchData"
      ></searchData>
    </KeepAlive>
  </div>
</template>

<script>
import { getSearch } from "@/api/find.js";
import searchData from "@/components/searchData.vue";
export default {
  name: "search",
  components: {
    searchData,
  },
  data() {
    return {
      show: true,
      listsearch: [],
      search: "",
      history: JSON.parse(localStorage.getItem("search"))
        ? JSON.parse(localStorage.getItem("search"))
        : [],
      data: [],
      categoryName: "hp",
      timer: null,
    };
  },
  methods: {
    // 历史记录的点击方法
    storys(i) {
      this.search = i;
      this.go();
    },
    // 接受子组件数据的方法
    changeSearchData(i) {
      console.log("接受到", i);
      this.categoryName = i;
      this.data = [];
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.timer = setTimeout(() => {
        this.go();
      }, 500);
    },
    // 搜索方法
    async go() {
      console.log("触发搜索");
      if (this.history.indexOf(this.search) !== -1) {
        console.log("有重复的", this.history.indexOf(this.search));
        this.history.splice(this.history.indexOf(this.search), 1);
      }
      this.history.unshift(this.search);
      localStorage.setItem("search", JSON.stringify(this.history));
      const { data } = await getSearch(this.categoryName, this.search, 0);
      this.data = data;
      console.log(data);
      this.show = false;
    },
  },
};
</script>

<style lang="less" scoped>
.search {
  width: 375px;
  height: 667px;
  background: #fff;
  .seatop {
    width: 100%;
    height: 50px;
    background: #f8f8f8;
    padding: 10px;
    display: flex;
    align-items: center;
    .inp {
      width: 300px;
      height: 30px;
      background: #fff;
      line-height: 30px;
      input {
        width: 100%;
        border: 0;
      }
    }
    span {
      font-size: 14px;
      color: #808080;
      margin-left: 10px;
    }
  }
  .content {
    padding: 15px;
    .his {
      margin-top: 10px;
      .history {
        display: inline-block;

        border: 1px solid #cecbcb;
        border-radius: 30px;
        color: #000;
        font-size: 14px;
        padding: 5px;
        margin: 5px;
      }
    }
  }
}
</style>